# Multi-stage build for optimized production image
FROM rust:1.75-slim as builder

# Install system dependencies
RUN apt-get update && apt-get install -y \
    pkg-config \
    libssl-dev \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# Create app directory
WORKDIR /app

# Copy manifests
COPY Cargo.toml Cargo.lock ./
COPY entity/Cargo.toml ./entity/
COPY migration/Cargo.toml ./migration/

# Create dummy source files to cache dependencies
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN mkdir entity/src && echo "" > entity/src/lib.rs
RUN mkdir migration/src && echo "fn main() {}" > migration/src/main.rs && echo "" > migration/src/lib.rs

# Build dependencies (this will be cached)
RUN cargo build --release
RUN rm -rf src entity/src migration/src

# Copy source code
COPY src ./src
COPY entity/src ./entity/src
COPY migration/src ./migration/src

# Build application
RUN touch src/main.rs entity/src/lib.rs migration/src/lib.rs migration/src/main.rs
RUN cargo build --release

# Runtime stage
FROM debian:bookworm-slim

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl3 \
    libpq5 \
    && rm -rf /var/lib/apt/lists/*

# Create app user
RUN groupadd -r appuser && useradd -r -g appuser appuser

# Create app directory
WORKDIR /app

# Copy binary from builder stage
COPY --from=builder /app/target/release/fm_best /usr/local/bin/fm_best
COPY --from=builder /app/target/release/migration /usr/local/bin/migration

# Copy configuration files
COPY config.toml ./config.toml

# Create necessary directories
RUN mkdir -p logs uploads && chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Run the application
CMD ["fm_best"]